<template>
  <el-dialog title="章节信息" :visible="true">
    <el-form>
      <el-form-item label="课程名称">
        <el-input v-model="courseName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="章节名称">
        <el-input v-model="sectionName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="课时名称">
        <el-input v-model="lesson.theme"></el-input>
      </el-form-item>

      <el-form-item label="时长">
        <el-input
          type="number"
          :min="0"
          v-model="lesson.duration"
        >
          <template slot="append">分钟</template>
        </el-input>
      </el-form-item>

      <el-form-item label="是否开放试听">
        <el-switch
          v-model="lesson.isFree"
          active-color="#13ce66"
          inactive-color="#ff4949">
        </el-switch>
      </el-form-item>

      <el-form-item label="章节排序">
        <el-input
          type="number"
          :min="0"
          v-model="lesson.orderNum"
        >
          <template slot="append">数字控制排序，数字越大越靠后</template>
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getLessonById, saveOrUpdateLesson } from '@/services/lesson'

  export default {
    name: 'CreateOrEditLesson',
    props: {
      courseId: {
        type: [Number, String],
        required: true,
      },
      courseName: {
        type: String,
        required: true,
      },
      sectionId: {
        type: [Number, String],
        required: true,
      },
      sectionName: {
        type: String,
        required: true,
      },
      lessonId: {
        type: [Number, String],
      }
    },
    data() {
      return {
        lesson: {
          theme: '',
          duration: 0,
          isFree: true,
          orderNum: 0,
        }
      }
    },
    created() {
      this.lessonId && this.loadLessonData()
    },
    methods: {
      async loadLessonData() {
        const { code, data } = await getLessonById(this.lessonId)
        if (code === '000000') {
          this.lesson = data
        }
      },
      async onSubmit() {
        const data = Object.assign(this.lesson, {
          courseId: this.courseId,
          sectionId: this.sectionId,
          duration: parseInt(this.lesson.duration),
        })
        const { code } = await saveOrUpdateLesson(data)
        if (code === '000000') {
          this.$message.success(`${this.sectionId ? '修改' : '添加'}成功！`)
          this.$emit('success')
        }
      }
    },
  }
</script>
